<?php
namespace app\backend\controller;
use app\backend\model\Admin;
use app\BaseController;
use think\captcha\facade\Captcha;
use think\facade\Session;
use think\middleware\SessionInit;
use think\facade\View;
use app\backend\model\Response;
class Register extends BaseController
{
    public function index() {
        return view();
    }

    private function registerUsernameAndPwd($username, $password): bool
    {
        if ($username == null || $password == null || strlen($username) == 0 || strlen($password) == 0) {
            return false;
        }
        $admin = new Admin();
        $admin->name = $username;
        $admin->password = md5($password);
        try {
            $admin->save();
            return true;
        } catch (\Exception $e) {
        }
        return false;
    }

    public function register() {
        $username = input('post.username');
        $password = input('post.password');
        $response = new Response();
        if ($this->registerUsernameAndPwd($username, $password)) {
            $response->success();
            $response->msg = "注册成功";
        } else {
            $response->msg = "注册失败，用户名已存在";
        }
        echo $response->toJson();
    }


}